import iapi from '@/libs/iapi';
import loading from '@/libs/loading';

let openid = '';
let _skey = '';
let userProfile = null;

//
let getOpenid = () => {
	return openid;
};

//这个uid代表用户是之前有过用户信息，但是没有手机号
let getSkey = () => {
	return _skey;
};


let getUserProfile = (cb) => {
	if (!cb) cb = {};

	uni.getUserProfile({
		desc: '用于同步会员信息',
		success: res => {
			let userInfo = res.userInfo;
			if (!userInfo) {
				cb.fail && cb.fail('501', '系统错误，请重试');
				return;
			}

			let user = {};
			user.name = userInfo.nickName;
			user.icon = userInfo.avatarUrl;
			user.country = userInfo.country;
			user.province = userInfo.province;
			user.city = userInfo.city;
			user.language = userInfo.language;

			userProfile = user;

			cb.succ && cb.succ(user);
		},
		fail: error => {
			cb.fail && cb.fail('505', error);
		},
	});

};


//通过openid登录
let login = (cb, appid, appstag) => {
	if (!cb) cb = {};

	if (!appid || !appstag) {
		let gData = getApp() && getApp().globalData ? getApp().globalData : {};
		if (gData.appid) appid = gData.appid;
		if (gData.appstag) appstag = gData.appstag;
	}

	if (!appid || !appstag) {
		cb.fail(101, '系统错误');
		return;
	}

	// #ifdef MP-WEIXIN
	loading.show('加载中');
	uni.login({
		provider: 'weixin',
		success: res => {
			let post = {};
			post.code = res.code;
			post.stag = appstag;
			post.appid = appid;

			//
			iapi.vapi('account/wxlogin', post, {
				succ: cb.succ,
				fail: cb.fail,
				ever: js => {
					loading.hide();

					if (!js || !js.data) return;

					if (js.data.openid) openid = js.data.openid;
					if (js.data._skey) _skey = js.data._skey;
				},
			});
		},
		fail: (code, msg) => {
			loading.hide();

			cb.fail(code, msg);
		},
	});
	return;
	// #endif

	cb.fail && cb.fail();
};


module.exports = {
	getOpenid,
	getUserProfile,
	getSkey,
	login,
}
